const fs = require('fs-extra');
const path = require('path');

const listExistFn = async (full_name) => {
  const file_src = path.join(__dirname, `../public/${full_name}`);
  try {
    const chunkPaths = await fs.readdir(file_src);
    return fs.existsSync(file_src) ?
      chunkPaths : [];
  } catch (error) {
    return [];
  }
}

const verify = async (ctx, next) => {
  const {
    hash_accept,
    file_name = ""
  } = ctx.request.body;
  const file_name_list = file_name.split('.');
  file_name_list.pop();

  const chunkPaths = await fs.readdir(path.join(__dirname, `../target`));
  const file_name_item = chunkPaths.find(v => v.includes(hash_accept));
  const full_name_src = `${hash_accept}_${file_name_list.join(".")}`;

  if (file_name_item) {
    ctx.body = {
      is_exist: true,
      hash_name: file_name_item,
      list_exist: []
    }
  } else {
    const chunkPaths = await listExistFn(full_name_src);

    ctx.body = {
      is_exist: false,
      hash_name: file_name_item,
      list_exist: chunkPaths
    }
  }
}

module.exports = verify;